<template>
  <!--  供应商-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="设备">
          <el-select v-model="searchParam.equipmentId" placeholder="请选择设备" style="width: 250px" filterable>
            <el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停机时间">
          <el-date-picker v-model="searchParam.times" type="datetimerange" start-placeholder="停机开始时间"
                          end-placeholder="停机结束时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 300px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize +
              scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentName" label="设备名称" align="center" min-width="200"/>
        <el-table-column prop="orgName" label="车间/产线" align="center" min-width="220"/>
        <el-table-column prop="ngType" :formatter="ngTypeFormatter" label="设备停机类型" align="center" min-width="200"/>
        <el-table-column prop="ngStartTime" label="停机开始时间" align="center" min-width="200"/>
        <el-table-column prop="ngEndTime" label="停机结束时间" align="center" min-width="200"/>
        <el-table-column prop="description" label="故障描述" align="center" min-width="200"/>
        <el-table-column prop="createTime" label="创建时间" align="center" min-width="200"/>
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small" plain :icon="Edit">编辑</el-button>
            <el-button @click="handleDel(scope.row)" text type="danger" size="small" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="1100px">
      <el-form :model="formData" label-width="auto" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item required label="选择设备" prop="equipmentId">
              <el-select v-model="formData.equipmentId" placeholder="请选择设备" style="width: 100%" filterable>
                <el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车间/产线" required prop="lineWorkShop">
              <el-tree-select v-model="formData.lineWorkShop" :data="workOptions" check-strictly
                              :render-after-expand="false" :props="{
									children: 'children',
									label: 'orgName',
									value: 'id',
								}" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <!-- 在el-form内添加表单项 -->
          <el-col :span="12">
            <el-form-item required label="是否计划停机" prop="isPlanStop">
              <el-select
                  v-model="formData.isPlanStop"
                  placeholder="请选择停机类型"
                  style="width: 100%"
              >
                <el-option label="计划内停机" :value="1"/>
                <el-option label="计划外停机" :value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="设备停机类型" prop="ngType">
              <el-select v-model="formData.ngType" placeholder="请选择设备停机类型" clearable style="width: 100%">
                <el-option v-for="(item, index) of ngTypeList" :key="index" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="停机时间" prop="times">
              <el-date-picker v-model="formData.times" type="datetimerange" start-placeholder="停机开始时间"
                              end-placeholder="停机结束时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障描述">
              <el-input v-model="formData.description" placeholder="请输入故障描述" clearable style="width:100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, computed, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useEquipmentData} from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Search, Share, Upload, Refresh, Plus, DocumentCopy} from '@element-plus/icons-vue';


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const configTableShow = ref(false);

const handleClick = (e) => {
  console.log(e, 'handleClick');
};

const showMaterial = ref(false);

// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    showConfig.value = false;
    showMaterial.value = false;
    // 刷新配置质检项列表
    getList();
  });
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';
import {lineAll} from '@/api/baseData/productionLine';

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: '',
  qualityWay: null,
  proportionNumber: 1,
  times: '',
  qualityType: '',
  qualityInterval: 1,
  ngType: true,
  description: '',
  isPlanStop: 1
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  equipmentId: [
    {required: true, message: '请选择设备', trigger: 'change'}
  ],
  lineWorkShop: [
    {required: true, message: '请选择车间/产线', trigger: 'change'}
  ],
  times: [
    {required: true, message: '请选择停机时间', trigger: 'change'}
  ],
  ngType: [
    {required: true, message: '请选择停机类型', trigger: 'change'}
  ],
  isPlanStop: [
    {required: true, message: '请选择停机类型', trigger: 'change'}
  ]
});


const paginatedData = ref([]);
const materialList = ref([]);//物料表


// 获取列表接口
const getList = () => {
  if (searchParam.value.times) {
    searchParam.value.ngStartTime = searchParam.value.times[0];
    searchParam.value.ngEndTime = searchParam.value.times[1];
  }

  axiosInstance.post('/api/equipmentNg/listPojoPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
  formData = reactive({});
  showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  const list = JSON.parse(JSON.stringify(row));
  list.times = [list.ngStartTime, list.ngEndTime];
  Object.assign(formData, list);
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/equipmentNg/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      console.log(formData);
      formData.ngStartTime = formData.times[0];
      formData.ngEndTime = formData.times[1];
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/equipmentNg/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        // formData.teamUserDTOS = {
        // 	userId: formData.teamUser
        // };
        // 新建
        formData.deptId = 1;
        formData.password = 1;

        axiosInstance.post('/api/equipmentNg/save', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};

const workOptions = ref([]);
const equipmentData = ref([]);
const ngTypeList = ref([{
  value: '1',
  label: '设备故障'
},
  {
    value: '2',
    label: '模具换型'
  }
]);

const ngTypeFormatter = (e) => {
  const type = ngTypeList.value.find(type => type.value == e.ngType);
  return type ? type.label : '';
};
// 获取列表数据
const getOptions = () => {
  workOptions.value = [];
  lineAll({current: 1, pageSize: 100000}).then((res) => {
    if (res.code === 200) {
      workOptions.value = buildTree(res.data.records.map((item) => {
        return {
          ...item.extension,
          ...item
        };
      }));
    }
  });

  axiosInstance.post('/api/basedataEquipment/getAll',
      {}
  ).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    equipmentData.value = res.data;
  });
};
const buildTree = (items) => {
  const itemMap = {};
  const rootItems = [];
  items.forEach((item) => {
    itemMap[item.id] = {...item, name: item.orgName, children: []};
  });
  items.forEach((item) => {
    if (!item.parentId || item.parentId === '0') {
      rootItems.push(itemMap[item.id]);
    } else {
      if (itemMap[item.parentId]) {
        itemMap[item.parentId].children.push(itemMap[item.id]);
      }
    }
  });

  return rootItems;
};

onMounted(() => {
  getList();
  getOptions();
});

</script>
<style scoped></style>
